package com.trip.service;

import com.trip.config.CommonProperties;
import com.trip.dao.tables.pojos.PicDomain;
import com.trip.dao.tables.records.PicRecord;
import com.trip.exception.ServiceException;
import com.trip.util.IDUtil;
import org.apache.commons.io.FileUtils;
import org.jooq.DSLContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.time.Instant;
import java.util.UUID;

import static com.trip.dao.Tables.PIC;

/**
 * Created by hc24 on 2017/10/7.
 */
@Service
@Transactional
public class PicService {

    @Autowired
    private DSLContext dslContext;

    @Autowired
    private CommonProperties properties;

    public void delPic(String picId){
        dslContext.deleteFrom(PIC).where(PIC.ID.eq(picId)).execute();
    }

    public PicDomain savePic(byte[] coverBytes, String ext, Integer type){
        return savePic(coverBytes,ext,type,null);
    }

    public PicDomain savePic(byte[] coverBytes, String ext, Integer type,String relatedId){
        ext=ext.indexOf(".")>-1?ext:"."+ext;
        String fileName=String.valueOf(UUID.randomUUID());
        String folderPath=properties.getPicConfig().getPicFolder();
        switch (type){
            case 1:
                if(relatedId==null)
                    folderPath+="/pae/";
                else
                    folderPath+="/"+relatedId+"/pae/";
                break;
            case 2:
                folderPath+="/user/";
                break;
            case 3:
                folderPath+="/plan/";
                break;
        }

        //save file
        File orgFile=new File(folderPath+fileName+ext);
        try {
            FileUtils.writeByteArrayToFile(orgFile,coverBytes);

            BufferedImage sourceImg = ImageIO.read(orgFile);

            if(type==1){
//                if(sourceImg.getWidth()<480){
//                    throw new ServiceException("The width of picture can't less than 480px");
//                }
//                if(sourceImg.getHeight()<800){
//                    throw new ServiceException("The height of picture can't less than 800px");
//                }
            }


            PicRecord picRecord= dslContext.newRecord(PIC);
            picRecord.setId(IDUtil.next());
            picRecord.setType(type);
            picRecord.setFileName(orgFile.getName());
            picRecord.setHeight(Double.valueOf(sourceImg.getHeight()));
            picRecord.setWidth(Double.valueOf(sourceImg.getWidth()));
            picRecord.insert();

            return picRecord.into(PicDomain.class);
        } catch (IOException e) {
            throw new ServiceException("IO error, please retry.");
        }

    }
}
